package com.lxj.sso.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lxj.sso.config.LxjConfig;
import com.lxj.sso.util.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;

/**
 * @ClassName AccessTokenController
 * @Description TODO
 * @Author wenqing_liu
 * @Date 2020/11/30 10:22
 */
@RestController
public class AccessTokenController {
    //解码
    private final static String ENCODE = "GBK";

    private final LxjConfig lxjConfig;

    public AccessTokenController(LxjConfig lxjConfig) {
        this.lxjConfig = lxjConfig;
    }

    @RequestMapping("/index")
    public String index() {
        return "登录成功";
    }

    @RequestMapping("/ssologin")
    public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取待办请求URL
        String redirectUrl = "";
        Enumeration<String> parameteNames = request.getParameterNames();
        while(parameteNames.hasMoreElements()) {
                String parameteName = parameteNames.nextElement();
                if (parameteName.equals("redirect")){
                    //获取待办请求URL
                    redirectUrl = request.getParameter("redirect");
                }
        }
        // 获取请求中带的token
        String token = request.getParameter("access_token");
        //对URL进行解码
        String encodeRedirectUrl = getURLDecoderString(redirectUrl);

        RestTemplate restTemplate = new RestTemplate();
        String portalUrl = lxjConfig.getPortal() + "/sso/auth/verify";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        JSONObject tokenJsonObj = new JSONObject();
        tokenJsonObj.put("token", token);
        String content = tokenJsonObj.toJSONString();
        // 构造request
        HttpEntity<String> requestNew = new HttpEntity<>(content, headers);
        // 验证URL参数中的token，是否有效
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(portalUrl, requestNew, String.class);
        JSONObject jsonObject = JSONObject.parseObject(stringResponseEntity.getBody());
        JSONObject userObject = jsonObject.getJSONObject("data");
        String userCode;
        if (userObject != null) {
            userCode = userObject.getString("user_code");
        } else {
            // 跳转到统一门户登录页
            response.sendRedirect(lxjConfig.getPortal());
            return;
        }

        // 获取appToken
        HttpClientUtils httpClientUtils = new HttpClientUtils(lxjConfig);
        String appToken = httpClientUtils.getAppToken();

        // 用接口账号获取 access_token ，用于查询手机号码
        JSONObject rootAccessTokenObject = httpClientUtils.getAccessToken(appToken, lxjConfig.getRootPhone());
        String rootAccessToken = rootAccessTokenObject.getString("access_token");

        // 根据手机号码，获取用户的access_token，用于登录苍穹系统
        String bosUserPhone = getBosUserPhone(rootAccessToken, userCode);
        if (StringUtils.isNotBlank(bosUserPhone)) {
            JSONObject userAccessTokenObject = httpClientUtils.getAccessToken(appToken, bosUserPhone);
            String userAccessToken = userAccessTokenObject.getString("access_token");
            // 判断userAccessToken 是否存在，如果存在即跳转到首页，如果不存在跳转到登陆页面
            if (StringUtils.isBlank(userAccessToken)) {
                response.sendRedirect(lxjConfig.getHomeUrl() + "/login.html?redirect=" + lxjConfig.getHomeUrl());
            } else {
                if(!redirectUrl.equals("")){
                    response.sendRedirect(lxjConfig.getHomeUrl() + "/accessTokenLogin.do?access_token=" + userAccessToken + "&redirect=" + encodeRedirectUrl);
                }else{
                    response.sendRedirect(lxjConfig.getHomeUrl() + "/accessTokenLogin.do?access_token=" + userAccessToken + "&redirect=" + lxjConfig.getHomeUrl() + "/?formId=pc_main_console");
                }
            }
        } else {
            response.sendRedirect(lxjConfig.getHomeUrl() + "/login.html?redirect=" + lxjConfig.getHomeUrl());
        }
    }

    public String getBosUserPhone(String accessToken, String userCode) throws IOException {

        // 构造 HttpClient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String queryUrl = lxjConfig.getHomeUrl() + "/kapi/sys/bos_user/query?select=phone&filter=" + URLEncoder.encode("number EQ " + userCode, "UTF-8") + "&access_token=" + accessToken;

        HttpGet httpGet = new HttpGet(queryUrl);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        org.apache.http.HttpEntity entity = response.getEntity();
        JSONArray dataArray = JSONObject.parseObject(EntityUtils.toString(entity)).getJSONObject("data").getJSONArray("rows");
        String userPhone = "";
        if (!dataArray.isEmpty()) {
            userPhone = dataArray.getJSONArray(0).getString(0);
        }
        return userPhone;
    }

    public static String getURLDecoderString(String url) {
        String result = "";
        if (null == url) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(url, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
